class ItemsController < ApplicationController

  before_filter :item_authorize
  
  def save
    item = params[:data][:item]
    Item.transaction do
      item = Item.create!(
        :location => Location.new(item[:location][:row], item[:location][:column]),
        :grid => @grid,
        :text => item[:text],
        :foreground_color => item[:foregroundColor],
        :background_color => item[:backgroundColor],
        :order => item[:order])
      item = {:data => ['itemSavedEvent', item.to_hash]}.to_json
      GridEvent.create(:data => item, :grid => @grid, :users => @users)
      head :ok  
    end
  end

  
  def destroy
    item = Item.find_top(params[:data][:gridId], params[:data][:location])
    Item.transaction do
      item.destroy
      item_hash = {:location => item.location}
      data = {:data => ['itemRemovedEvent', item_hash]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  
  def update
    item = Item.find_top(params[:data][:gridId], params[:data][:item][:location])
    Item.transaction do
      item.update_attributes!(params[:data][:item])
      data = {:data => ['itemUpdatedEvent', item.to_hash]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  def move_item
    data = params[:data]
    item = Item.find_top(data[:gridId], data[:oldLocation])
    item.location = Location.adapt(data[:newLocation])
    item.order = data[:order]
    Item.transaction do
      item.save!
      data = {:data => ['itemMovedEvent', data]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  def move_stack
    data = params[:data]
    Item.transaction do
      Item.move_stack(data[:gridId], data[:oldLocation], data[:newLocation])
      data = {:data => ['stackMovedEvent', data]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  def set_top_item
    data = params[:data]
    Item.transaction do
      Item.set_top_item(data[:gridId], data[:location], data[:order])
      data = {:data => ['topItemSetEvent', data]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  def change_dimensions
    data = params[:data]
    Grid.transaction do
      grid = Grid.find(data[:gridId])
      rows = data[:rows]
      columns = data[:columns]
      grid.change_dimensions(rows.to_i, columns.to_i)
      data = {:data => ['dimensionsChangedEvent', data]}.to_json
      GridEvent.create(:data => data, :grid => @grid, :users => @users)
      head :ok
    end
  end

  private

  def item_authorize
    head :forbidden if (current_user.account_type != 'operator')
  end

end
